package com.rock.code.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rock.code.common.comm.RandomGUID;
import com.rock.code.datacollconfig.h3c.dao.TbCdeKbpDao;
import com.rock.code.datacollconfig.h3c.dao.TbConfIpsDao;
import com.rock.code.datacollconfig.h3c.domain.TB_CONF_NET_KPI;
import com.rock.code.datacollconfig.h3c.domain.TbConfIps;
import com.rock.code.datacollconfig.h3c.domain.TbConfNetIp;
import com.rock.code.datacollconfig.h3c.domain.TblATO_KPIDETAIL;
import com.rock.code.datacollconfig.h3c.domain.alarm.AlarmBean;
import com.rock.code.datacollconfig.h3c.domain.alarm.FaultBean;
import com.rock.code.datacollconfig.h3c.domain.perf.PerfSummaryBean;
import com.rock.code.datacollconfig.h3c.domain.perf.PerfSummaryDataBean;
import com.rock.code.datacollconfig.h3c.domain.res.DeviceAllBean;
import com.rock.code.datacollconfig.h3c.domain.res.DeviceSimpleBean;
import com.rock.code.province.tj.busi.socketdr.Producer;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;

/**
 * @author wuzeyuan
 * @date 20190307
 */
public class IMCUtil {
    
    private static Logger logger = Logger.getLogger("COLL");
    private static ResourceBundle LoginInfo = ResourceBundle.getBundle("h3c");
    private static String IP = "20.58.10.129";
    private static int PORT = 80;
    private static String URL = "http://20.58.10.129/imcrs";
    private static String URI = "/plat/res/device";
    private static long LAST_TIME = System.currentTimeMillis();
    private static String USERNAME = "admin";
    private static String PASSWORD = "benqfp71g+";
    private static String PATH = "/home/collstd/itnmsapp/masteragent/swap/";
    private static String CHARSET = "utf-8";
    private static int RELOADTIME = 600000;
    
    static {
        try {
            IP = LoginInfo.getString("ip");
            PORT = Integer.parseInt(LoginInfo.getString("port"));
            URL = "http://" + IP + ":" + PORT + LoginInfo.getString("prefix");
            USERNAME = LoginInfo.getString("user");
            PASSWORD = LoginInfo.getString("pwd");
            PATH = LoginInfo.getString("path");
            CHARSET = LoginInfo.getString("charset");
            RELOADTIME = Integer.parseInt(LoginInfo.getString("realtimerinterval"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 指定时间初始化 h3c iMC
     */
    public static void init() {
        if (System.currentTimeMillis() - LAST_TIME > RELOADTIME) {
            // 加载配置参数
            IP = LoginInfo.getString("ip");
            PORT = Integer.parseInt(LoginInfo.getString("port"));
            URL = "http://" + IP + ":" + PORT + LoginInfo.getString("prefix");
            USERNAME = LoginInfo.getString("user");
            PASSWORD = LoginInfo.getString("pwd");
            PATH = LoginInfo.getString("path");
            CHARSET = LoginInfo.getString("charset");
            RELOADTIME = Integer.parseInt(LoginInfo.getString("realtimerinterval"));
            LAST_TIME = System.currentTimeMillis();
        }
    }
    
    @Autowired
    private TbConfIpsDao tbConfIpsDao;
    @Autowired
    private TbCdeKbpDao tbCdeKbpDao;
    
    /**
     * 获取所有网络设备相关信息（IP）
     */
    public List getIpsByParams() throws Exception {
        tbConfIpsDao = (TbConfIpsDao) SpringContextUtil.getBeanByClass(TbConfIpsDao.class);
        tbCdeKbpDao = (TbCdeKbpDao) SpringContextUtil.getBeanByClass(TbCdeKbpDao.class);
        //调用接口，获取总条数
        int size = total(URI, false);
        System.out.println("设备总数:" + size);
        //调用接口，获取所有设备信息（带分页参数）
        JSONObject jsonListObject = httpGet(URI + "?size=" + size);
        //转为List
        JSONArray allList = (JSONArray) jsonListObject.get("device");
        List<TbConfIps> ips = new ArrayList();
        for (int i = 0; i < allList.size(); i++) {
            Map<String, Object> maps = (Map<String, Object>) allList.get(i);
            String label = (String) maps.get("label");//NAME
            String ip = (String) maps.get("ip");//设备IP
            //根据IP查询设备
            JSONObject json = getDeviceByIp(ip);
            Map<String, Object> map = (Map) json.get("category");
            String category = (String) map.get("id");//设备类型
            Map<String, Object> deviceSeries = (Map) json.get("deviceSeries");
            String vendorId = (String) deviceSeries.get("id");
            String vendorName = getVendorById(vendorId);//厂商
            String enable = "1";//开关
            String kbp;
            
            //判断设备类型，拼接kbp前两位
            List<String> kbp_categorys = tbCdeKbpDao.getCategory(category);
            String kbp_category;
            if (kbp_categorys.size() > 1) {
                logger.warn("Error:KBP第二位重复配置");
                continue;
            } else {
                kbp_category = kbp_categorys.get(0);
            }
            if (kbp_category == null || "".equals(kbp_category)) {
                continue;
            }
            //            if ("0".equals(category)) {//路由器
            //                kbp = "10-17";
            //            } else if ("1".equals(category)) {//交换机
            //                kbp = "10-16";
            //            } else if ("3".equals(category)) {//安全设备
            //                kbp = "10-18";
            //            } else if ("10".equals(category)) {//其他SNMP设备
            //                kbp = "10-20";
            //            } else if ("15".equals(category)) {//应用控制器(负载均衡)
            //                kbp = "10-19";
            //            } else {
            //                kbp = "10-233";
            //                continue;
            //            }
            
            //判断厂商，拼接kbp第三位
            List<String> kbp_vendors = tbCdeKbpDao.getVendor(vendorId, kbp_category);
            String kbp_vendor = null;
            if (kbp_vendors.size() > 1) {
                System.out.println("Error:KBP第三位重复配置");
            } else {
                kbp_vendor = kbp_vendors.get(0);
            }
            if (kbp_vendor == null || "".equals(kbp_vendor)) {
                kbp_vendor = kbp_category + "-01";
            }
            kbp = kbp_vendor;
            
            //            if ("H3C".equals(vendorName)) {
            //                kbp = kbp + "-14";
            //            } else if ("Cisco".equals(vendorName)) {
            //                kbp = kbp + "-10";
            //            } else if ("Huawei".equals(vendorName)) {
            //                kbp = kbp + "-11";
            //            } else if ("Hewlett Packard".equals(vendorName)) { //HP
            //                kbp = kbp + "-15";
            //            } else if ("IBM".equals(vendorName)) {
            //                kbp = kbp + "-13";
            //            } else if ("Unknown".equals(vendorName)) {
            //                kbp = kbp + "-32";
            //            } else if ("Citrix".equals(vendorName)) {
            //                kbp = kbp + "-31";
            //            } else if ("F5".equals(vendorName)) {
            //                kbp = kbp + "-30";
            //            } else {
            //                kbp = kbp + "-233";
            //            }
            //封装对象参数
            TbConfIps tbConfIps = new TbConfIps();
            tbConfIps.setId(RandomGUID.getRandomGUID());
            tbConfIps.setName(label);
            tbConfIps.setIp(ip);
            tbConfIps.setVendor(vendorName);
            tbConfIps.setCategory(category);
            tbConfIps.setEnable(enable);
            tbConfIps.setKbp(kbp);
            tbConfIps.setSource("H3C");
            //add
            ips.add(tbConfIps);
            //插入数据
            List list = tbConfIpsDao.queryList(tbConfIps);
            if (list.size() == 0) {
                tbConfIpsDao.insert(tbConfIps);
            }
            System.out.println("设备" + (i + 1) + ":" + label + "-.-.-" + ip + "-.-.-" + vendorName + "-.-.-" + category + "-.-.-" + enable + "-.-.-" + kbp);
        }
        return ips;
    }
    
    /**
     * 调用华3网管接口
     */
    public static JSONObject httpGet(String uri) {
        return HttpRequestUtils.httpGet(URL + uri, IP, PORT, USERNAME, PASSWORD);
    }
    
    /**
     * 总记录数
     *
     * @param exact 是否通过IP进行精确查询
     *
     * @author wuzeyuan
     * @date 20190308  Total int.
     */
    public static int total(String uri, boolean exact) {
        String value;
        if (exact) {
            value = HttpRequestUtils.httpHeaderGet("total", URL + uri + "?total=true&exact=true", IP, PORT, USERNAME, PASSWORD);
        } else {
            value = HttpRequestUtils.httpHeaderGet("total", URL + uri + "?total=true", IP, PORT, USERNAME, PASSWORD);
        }
        return Integer.parseInt(value != null ? value : "0");
    }
    
    public static int total(String uri) {
        return total(uri, false);
    }
    
    /**
     * 查询设备信息列表
     */
    public static JSONObject listDevices() {
        String uri = "/plat/res/device";
        return httpGet(uri);
    }
    
    /**
     * 通过一些参数查询设备信息列表
     */
    public static JSONObject listDevices(String uri) {
        // String uri = "/plat/res/device?ip=10.231.248.25";
        // String uri = "/plat/res/device/8";
        // String uri = "/plat/res/device/allMsg/10.230.0.77";
        return httpGet(uri);
    }
    
    /**
     * 通过厂商ID查询设备厂商信息
     */
    public static String getVendorById(String id) {
        String uri = "/plat/res/vendor/" + id;
        JSONObject jsonObject = httpGet(uri);
        return jsonObject.getString("name");
    }
    
    /**
     * 通过IP查询设备
     */
    public static JSONObject listDevicesByIp(String ip) {
        // String uri = "/plat/res/device?ip=10.231.248.25";
        return httpGet(URI + "?ip=" + ip);
    }
    
    /**
     * 通过IP查询单个设备的详细信息
     */
    public static JSONObject getDeviceByIp(String ip) {
        // String uri = "/plat/res/device/allMsg/10.231.248.25";
        return httpGet(URI + "/allMsg/" + ip);
    }
    
    /**
     * 查询性能
     *
     * @param devId  设备ID
     * @param taskId 性能任务ID，可以通过 /perf/task 得到任务列表
     */
    public static JSONObject listPerf(String devId, String taskId) {
        String uri = "/perf/summaryData?devId=" + devId + "&taskId=" + taskId + "&dataGranularity=" + 1;
        return httpGet(uri);
    }
    
    /**
     * 查询告警
     *
     * @param devId 设备ID
     */
    public static JSONObject listAlarm(String devId) {
        String uri = "/fault/alarm?operatorName=admin&deviceId=" + devId + "&size=100&desc=false";
        return httpGet(uri);
    }
    
    /**
     * 解析配置(CM) JSON 并转为 TblATO_KPIDETAIL
     */
    public static List<TblATO_KPIDETAIL> parseDevAllJSON(JSONObject json, String kbp, TB_CONF_NET_KPI k, Map<String, String> ifIndex) {
        if (json == null || json.size() < 1 || kbp == null || "".equals(kbp) || k == null) {
            logger.info("配置指标为空");
            return null;
        }
        List<TblATO_KPIDETAIL> kpiList = new ArrayList<>();
        try {
            Gson gson = new Gson();
            String jsonString = json.toJSONString().replaceAll(",\\s*\"ipHash\":\\s*\\[.*?\\]\\s*\\}\\s*\\]\\s*", "");
            DeviceAllBean device = gson.fromJson(jsonString, DeviceAllBean.class);
            TblATO_KPIDETAIL kpi = new TblATO_KPIDETAIL();
            String unitId = kbp + "-" + k.getKBP() + "-H3C" + ":" + device.getIp().replace(".", "_");
            String type = k.getTYPE();
            String key = k.getKEY();
            logger.debug("key:" + key);
            // 如果是接口指标
            if (key != null && !"".equals(key) && key.contains("interfaces")) {
                // 接口数量
                if (key.contains("size")) {
                    kpi.setUNIT_ID(unitId + "-" + type);
                    kpi.setKPI_ID(k.getKPI_ID());
                    kpi.setKPI_VALUE(String.valueOf(device.getInterfaces().size()));
                    kpi.setCLL_TIME_STR(device.getLastPoll());
                    kpi.setEXT_INFO(device.getLabel());
                    kpiList.add(kpi);
                } else {
                    for (int i = 0; i < device.getInterfaces().size(); i++) {
                        try {
                            TblATO_KPIDETAIL _kpi = new TblATO_KPIDETAIL();
                            String value = getIfValuesByKey(json, key, i);
                            String name = getIfValuesByKey(json, "interfaces.ifDescription", i);
                            // 处理接口名不匹配的问题
                            if (!name.contains("GigabitEthernet")) {
                                String index = getIfValuesByKey(json, "interfaces.ifIndex", i);
                                ifIndex.put(index, name);
                            }
                            _kpi.setUNIT_ID(unitId + "-" + name);
                            _kpi.setKPI_ID(k.getKPI_ID());
                            _kpi.setKPI_VALUE(value);
                            _kpi.setCLL_TIME_STR(device.getLastPoll());
                            _kpi.setEXT_INFO(device.getLabel());
                            kpiList.add(_kpi);
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }
            }
            // 如果是系统信息指标 指标值有回车
            else if (key != null && !"".equals(key) && key.contains("sysDescription")) {
                kpi.setUNIT_ID(unitId + "-" + type);
                kpi.setKPI_ID(k.getKPI_ID());
                kpi.setKPI_VALUE(getValueByKey(json, key).replaceAll("\\s", " "));
                kpi.setCLL_TIME_STR(device.getLastPoll());
                kpi.setEXT_INFO(device.getLabel());
                kpiList.add(kpi);
            } // 如果是厂商指标
            else if (key != null && !"".equals(key) && key.contains("vendor")) {
                kpi.setUNIT_ID(unitId + "-" + type);
                kpi.setKPI_ID(k.getKPI_ID());
                kpi.setKPI_VALUE(getVendorById(getValueByKey(json, key)));
                kpi.setCLL_TIME_STR(device.getLastPoll());
                kpi.setEXT_INFO(device.getLabel());
                kpiList.add(kpi);
            } else {
                kpi.setUNIT_ID(unitId + "-" + type);
                kpi.setKPI_ID(k.getKPI_ID());
                kpi.setKPI_VALUE(getValueByKey(json, key));
                kpi.setCLL_TIME_STR(device.getLastPoll());
                kpi.setEXT_INFO(device.getLabel());
                kpiList.add(kpi);
            }
            logger.info("解析配置完成");
            return kpiList;
        } catch (Exception e) {
            logger.error("解析配置失败");
            e.printStackTrace();
            return kpiList;
        }
    }
    
    /**
     * 通过key获取性能
     */
    public static String getValueByKey(JSONObject json, String key) {
        if (key == null || "".equals(key)) {
            return "";
        }
        String value = "";
        String[] ms = key.split("\\.");
        int l = ms.length;
        if (l == 1) {
            value = json.getString(ms[0]);
        } else if (l == 2) {
            value = json.getJSONObject(ms[0]).getString(ms[1]);
        }
        return value;
    }
    
    /**
     * 通过key，index获取接口性能
     */
    public static String getIfValuesByKey(JSONObject json, String key, int i) {
        String[] ms = key.split("\\.");
        int l = ms.length;
        String value = null;
        if (l == 2) {
            value = json.getJSONArray(ms[0]).getJSONObject(i).getString(ms[1]);
        }
        // IP 或掩码
        else if (l == 4) {
            JSONObject interfaceJson = json.getJSONArray(ms[0]).getJSONObject(i);
            JSONObject ipHashJson = interfaceJson.getJSONObject(ms[1]);
            JSONArray itemJson = ipHashJson.getJSONArray(ms[2]);
            value = itemJson.getString(Integer.parseInt(ms[3]));
        }
        return value;
    }
    
    /**
     * 解析性能(PM) JSON 并转为 TblATO_KPIDETAIL
     */
    public static List<TblATO_KPIDETAIL> parsePerfJSON(JSONObject json, String kbp, TB_CONF_NET_KPI k, String ip, Map<String, String> ifIndex) {
        if (json == null || json.size() < 1 || kbp == null || "".equals(kbp) || k == null || ip == null || "".equals(ip)) {
            logger.info("性能指标为空");
            return null;
        }
        List<TblATO_KPIDETAIL> kpiList = new ArrayList<>();
        try {
            String kpiId = k.getKPI_ID();
            String unitId = kbp + "-" + k.getKBP() + "-H3C" + ":" + ip.replace(".", "_");
            Gson gson = new Gson();
            PerfSummaryBean perfs = gson.fromJson(json.toJSONString(), PerfSummaryBean.class);
            for (PerfSummaryDataBean perf : perfs.getPerfSummaryData()) {
                if (perf.getAverageValue() == null) {
                    continue;
                }
                TblATO_KPIDETAIL kpi = new TblATO_KPIDETAIL();
                String type = k.getTYPE();
                if ("interface".equals(type)) {
                    // [接口:Ten-GigabitEthernet0/4/2] > Ten-GigabitEthernet0/4/2
                    String name = perf.getObjIndexDesc().trim();
                    if (name.startsWith("[接口:")) {
                        int l = name.length();
                        try {
                            if (l <= 6) {
                                // 处理接口名不匹配的问题 例如:[接口:2
                                kpi.setUNIT_ID(unitId + "-" + ifIndex.get(perf.getObjIndex()));
                            } else {
                                kpi.setUNIT_ID(unitId + "-" + name.substring(4, l - 1));
                            }
                        } catch (StringIndexOutOfBoundsException e) {
                            logger.info("名称长度错误");
                        }
                    } else {
                        kpi.setUNIT_ID(unitId + "-" + name);
                    }
                } else {
                    kpi.setUNIT_ID(unitId + "-" + type);
                }
                kpi.setKPI_ID(kpiId);
                kpi.setKPI_VALUE(perf.getAverageValue());
                kpi.setCLL_TIME_STR(perf.getDetailData().getDataTimeStr());
                kpi.setEXT_INFO(perf.getTaskName());
                kpiList.add(kpi);
            }
            logger.info("解析性能完成");
            return kpiList;
        } catch (Exception e) {
            logger.info("解析性能失败");
            e.printStackTrace();
            return kpiList;
        }
    }
    
    /**
     * 解析告警(FM) JSON 并转为 TblATO_KPIDETAIL
     */
    public static List<TblATO_KPIDETAIL> parseAlarmJSON(JSONObject json, String kbp) {
        if (json == null || json.size() < 1 || kbp == null || "".equals(kbp)) {
            logger.info("没有告警");
            return null;
        }
        List<TblATO_KPIDETAIL> kpiList = new ArrayList<>();
        try {
            String alarmJsonString = json.getString("alarm");
            Gson gson = new Gson();
            if (alarmJsonString == null || "".equals(alarmJsonString)) {
                logger.info("没有告警");
                return null;
            }
            // 多个告警
            else if (alarmJsonString.startsWith("[")) {
                FaultBean fault = gson.fromJson(json.toJSONString(), FaultBean.class);
                for (AlarmBean alarm : fault.getAlarm()) {
                    kpiList.add(generateAlarmKpi(kbp, alarm));
                }
            }
            // 单个告警
            else {
                AlarmBean alarm = gson.fromJson(alarmJsonString, AlarmBean.class);
                kpiList.add(generateAlarmKpi(kbp, alarm));
            }
            logger.info("解析告警完成");
            return kpiList;
        } catch (Exception e) {
            logger.info("解析告警失败");
            e.printStackTrace();
            return kpiList;
        }
    }
    
    /**
     * 生成告警指标
     */
    private static TblATO_KPIDETAIL generateAlarmKpi(String kbp, AlarmBean alarm) {
        TblATO_KPIDETAIL kpi = new TblATO_KPIDETAIL();
        String unitId = kbp + "-10:" + alarm.getDeviceIp().replace(".", "_") + "-" + alarm.getOID() + "-alarm";
        kpi.setUNIT_ID(unitId);
        String kpiId = "FM-" + kbp + "-" + alarm.getAlarmCategory();
        kpi.setKPI_ID(kpiId);
        kpi.setKPI_VALUE(alarm.getAlarmDesc());
        kpi.setCLL_TIME_STR(alarm.getFaultTimeDesc());
        kpi.setEXT_INFO(alarm.getDeviceName());
        return kpi;
    }
    
    /**
     * 采集入口
     *
     * @param ips  需要采集的所有资源的IP
     * @param kpis 每种资源需要采集的KPI
     */
    public static void coll(List<TbConfNetIp> ips, List<TB_CONF_NET_KPI> kpis) {
        if (ips == null || kpis == null) {
            return;
        }
        init();
        // 遍历所有IP
        for (TbConfNetIp i : ips) {
            List<TblATO_KPIDETAIL> all = new ArrayList<>();
            String ip = i.getIp();
            logger.info("DevIp:" + ip);
            JSONObject devJson = listDevicesByIp(ip);
            if (devJson == null) {
                logger.error(ip + "采集失败");
                continue;
            }
            String devJsonString = devJson.getString("device");
            // 取得设备ID
            String devId = null;
            Gson gson = new Gson();
            if (devJsonString == null || "".equals(devJsonString)) {
                continue;
            } else if (devJsonString.startsWith("[")) {
                List<DeviceSimpleBean> devices = gson.fromJson(devJsonString, new TypeToken<List<DeviceSimpleBean>>() {
                }.getType());
                // 匹配当前IP,一些设备有多个IP
                for (DeviceSimpleBean deviceSimpleBean : devices) {
                    if (ip.equals(deviceSimpleBean.getIp())) {
                        devId = deviceSimpleBean.getId();
                        break;
                    } else {
                        devId = deviceSimpleBean.getId();
                    }
                }
            } else {
                DeviceSimpleBean device = gson.fromJson(devJsonString, DeviceSimpleBean.class);
                devId = device.getId();
            }
            if (devId == null) {
                continue;
            }
            logger.info("DevId:" + devId);
            Map<String, String> ifIndex = new HashMap();
            // 遍历所有指标
            for (TB_CONF_NET_KPI k : kpis) {
                String kpiId = k.getKPI_ID();
                if (kpiId == null || "".equals(kpiId)) {
                    continue;
                }
                logger.info("KpiId:" + kpiId + "\t" + k.getKPI_NAME());
                // 配置
                if (kpiId.startsWith("CM")) {
                    JSONObject devAllJson = getDeviceByIp(ip);
                    List<TblATO_KPIDETAIL> kpiList = parseDevAllJSON(devAllJson, i.getKbp(), k, ifIndex);
                    if (kpiList != null) {
                        all.addAll(kpiList);
                    }
                }
                // 性能
                else if (kpiId.startsWith("PM")) {
                    String taskId = k.getTASK_ID();
                    if (taskId == null || "".equals(taskId)) {
                        continue;
                    }
                    logger.info("TaskId:" + taskId);
                    JSONObject perfJson = listPerf(devId, taskId);
                    List<TblATO_KPIDETAIL> kpiList = parsePerfJSON(perfJson, i.getKbp(), k, ip, ifIndex);
                    if (kpiList != null) {
                        all.addAll(kpiList);
                    }
                }
            }
            // 处理告警
            // JSONObject alarmJson = listAlarm(devId);
            // List<TblATO_KPIDETAIL> kpiList = parseAlarmJSON(alarmJson, i.getKbp());
            // if (kpiList != null) {
            //     all.addAll(kpiList);
            // }
            // saveFile(all);
            
            // 往kafka推送数据
            sendData(all);
        }
    }
    
    /**
     * 往kafka推送数据
     */
    private static void sendData(List<TblATO_KPIDETAIL> list) {
        if (list == null) {
            return;
        }
        StringBuffer sFileContent = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            TblATO_KPIDETAIL tblATO_KPIDETAIL = list.get(i);
            sFileContent.append(tblATO_KPIDETAIL.getUNIT_ID());
            sFileContent.append("	");
            sFileContent.append(tblATO_KPIDETAIL.getKPI_ID());
            sFileContent.append("	");
            sFileContent.append(tblATO_KPIDETAIL.getCLL_TIME_STR());
            sFileContent.append("	");
            String value = tblATO_KPIDETAIL.getKPI_VALUE();
            sFileContent.append("".equals(value) ? "null" : value);
            sFileContent.append("	");
            sFileContent.append(tblATO_KPIDETAIL.getINTERVAL());
            sFileContent.append("	");
            sFileContent.append(tblATO_KPIDETAIL.getEXT_INFO());
            sFileContent.append("\n");
        }
        Producer producer = new Producer();
        producer.produce(sFileContent.toString());
    }
    
    /**
     * 将采集到的 KPI 存入文件
     *
     * @author wuzeyuan
     * @date 20190307  Save file.
     */
    public static void saveFile(List<TblATO_KPIDETAIL> list) {
        if (list == null) {
            return;
        }
        String kpiFileName = System.currentTimeMillis() + "-" + new Random().nextInt(100);
        File kpiFile = new File(PATH.endsWith(File.separator) ? PATH + kpiFileName : PATH + File.separator + kpiFileName);
        logger.info("指标文件:" + kpiFile.getAbsolutePath());
        StringBuffer sFileContent = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            TblATO_KPIDETAIL tblATO_KPIDETAIL = list.get(i);
            sFileContent.append(tblATO_KPIDETAIL.getUNIT_ID());
            sFileContent.append("	");
            sFileContent.append(tblATO_KPIDETAIL.getKPI_ID());
            sFileContent.append("	");
            sFileContent.append(tblATO_KPIDETAIL.getCLL_TIME_STR());
            sFileContent.append("	");
            String value = tblATO_KPIDETAIL.getKPI_VALUE();
            sFileContent.append("".equals(value) ? "null" : value);
            sFileContent.append("	");
            sFileContent.append(tblATO_KPIDETAIL.getINTERVAL());
            sFileContent.append("	");
            sFileContent.append(tblATO_KPIDETAIL.getEXT_INFO());
            sFileContent.append("\n");
        }
        // 写文件
        if (!"".equals(kpiFileName) && !"".contentEquals(sFileContent)) {
            logger.info("KPI:" + sFileContent);
            try {
                FileOutputStream fos = new FileOutputStream(kpiFile);
                OutputStreamWriter osw = new OutputStreamWriter(fos, CHARSET);
                BufferedWriter fw = new BufferedWriter(osw);
                fw.write(sFileContent.toString());
                fw.flush();
                fw.close();
                osw.close();
                fos.close();
            } catch (IOException e) {
                logger.error("[iMC COLL] Exception while saveFile", e);
            }
        }
    }
    
    /**
     * 限定参数
     */
    public static String locationParameter(Map<String, String> params) {
        StringBuilder buff = new StringBuilder();
        if (params == null) {
            return buff.toString();
        } else {
            buff.append("?");
            for (Map.Entry<String, String> e : params.entrySet()) {
                buff.append(e.getKey());
                buff.append("=");
                buff.append(e.getValue());
                buff.append("&");
            }
            buff.deleteCharAt(buff.length() - 1);
            return buff.toString();
        }
    }
    
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
        TbCdeKbpDao tbCdeKbpDao = context.getBean("tbCdeKbpDao", TbCdeKbpDao.class);
        List<String> kbp_categorys = tbCdeKbpDao.getCategory("0");
        System.out.println(kbp_categorys.get(0));
        
        List<String> kbp_vendors = tbCdeKbpDao.getVendor("0", kbp_categorys.get(0));
        System.out.println(kbp_vendors.get(0));
    }
}
